# -*- encoding: utf-8 -*-
# @Time       :  19:25
# @Author     : yuxian
# @Email      : 1503889663@qq.com
# @File       : app.py
# @SoftWare   : PyCharm
import logging
from logging.handlers import RotatingFileHandler

from flask import Flask, request, jsonify

app = Flask(__name__)

# 设置日志级别
logging.basicConfig(level=logging.DEBUG)

# 创建文件处理器，并设置日志级别和日志格式
log_handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=3)
log_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)s:%(name)s: %(message)s')
log_handler.setFormatter(formatter)
# 添加处理器到应用的日志器中
app.logger.addHandler(log_handler)


# 功能列表接口
@app.route('/', methods=['GET'])
def home():
    functions = {
        "API文档": [{'中译英': '/translate/zh-to-en', 'params': "type|string;name|text", 'method': "POST"},
                    {'英译中': '/translate/en-to-zh', 'params': "type|string;name|text", 'method': "POST"},
                    {'总结': '/summarize', 'params': "type|string;name|text", 'method': "POST"}]
    }
    return jsonify(functions)


# 中译英接口
@app.route('/translate/zh-to-en', methods=['POST'])
def translate_zh_to_en():
    data = request.json
    text = data.get('text')
    if not text:
        return jsonify({'msg': "text字段不能为空！"}), 400
    try:
        translated_text = translate(text, "zh", "en")
    except Exception as e:
        logging.error("[/translate/zh-to-en][%s][%s]" % (text, e))
        return jsonify(
            {'translated_text': None, 'status': "error", 'msg': "服务器出错了，请联系管理员，或者稍后重试！"}), 400
    return jsonify({'translated_text': translated_text, 'status': "success"})


# 英译中接口
@app.route('/translate/en-to-zh', methods=['POST'])
def translate_en_to_zh():
    data = request.json
    text = data.get('text')
    if not text:
        return jsonify({'msg': "text字段不能为空！"}), 400
    try:
        translated_text = translate(text, "en", "zh")
    except Exception as e:
        logging.error("[/translate/en-to-zh][%s][%s]" % (text, e))
        return jsonify({'translated_text': None, 'status': "error", 'msg': "服务器出错了，请联系管理员，或者稍后重试！"}), 500
    return jsonify({'translated_text': translated_text, 'status': "success"})


# 总结接口
@app.route('/summarize', methods=['POST'])
def summarize():
    data = request.json
    text = data.get('text')
    if not text:
        return jsonify({'msg': "text字段不能为空！"}), 400
    try:
        summary = summarize_text(text)
    except Exception as e:
        logging.error("[/summarize][%s][%s]" % (text, e))
        return jsonify({'summary': None, 'status': "error", 'msg': "服务器出错了，请联系管理员，或者稍后重试！"}), 500
    return jsonify({'summary': summary, 'status': "success"})


def translate(text, source_lang, target_lang):
    # 调用翻译模型的代码
    return f"Translated '{text}' from {source_lang} to {target_lang}"


def summarize_text(text):
    # 调用总结模型部分的代码
    return f"Summary of '{text}'"


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5700)
